package com.ruoyi.server;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
//💻 客服（MyWebSocketHandler）：实际处理用户问题的员工
//@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
//    记录所有正在通话的用户
    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
    private static final Map<WebSocketSession, String> userRoles = new ConcurrentHashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String role = (String) session.getAttributes().get("role");
        userRoles.put(session, role);
        sessions.add(session);
        sendMessage(session, "连接成功，您的身份是：" + role);
    }

    // 当用户说话时（收到消息）
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        Map payloadMap = JSONObject.parseObject(payload);
        JSONObject json = new JSONObject(payloadMap);// 获取用户说的话

        // 根据消息类型处理业务逻辑
        if ("chat".equals(json.getString("type"))) {
            String content = json.getString("content");
            broadcastMessage("用户说：" + content);// 广播给所有人
        }
        String role = userRoles.get(session);
        if ("admin".equals(role) && payload.startsWith("/broadcast ")) {
            String content = payload.substring(11);
            broadcastToAll("[管理员通知] " + content);
        } else {
            broadcastToAll("用户消息：" + payload);
        }
    }
    private void broadcastToAll(String message) {
        sessions.forEach(s -> {
            try {
                if (s.isOpen()) {
                    s.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
        userRoles.remove(session);
    }

    // 群发消息给所有人（广播）
    private void broadcastMessage(String message) {
        sessions.forEach(session -> {
            if (session.isOpen()) {
                sendMessage(session, message);
            }
        });
    }

    private void sendMessage(WebSocketSession session, String message) {
        try {
            session.sendMessage(new TextMessage(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}